# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from config import Config
from flask import request, abort, Blueprint
from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wechatpy.exceptions import (
    InvalidSignatureException,
    InvalidAppIdException,
)
from ..api import CamServer
# 设定蓝图 index
mod = Blueprint('wechat', __name__)


# 消息入口
@mod.route('/', methods=['get', 'post'])
def message_entries():
    signature = request.args.get('signature', '')
    timestamp = request.args.get('timestamp', '')
    nonce = request.args.get('nonce', '')
    encrypt_type = request.args.get('encrypt_type', 'raw')
    msg_signature = request.args.get('msg_signature', '')
    camera = CamServer.CamService()
    try:
        check_signature(Config.TOKEN, signature, timestamp, nonce)
    except InvalidSignatureException:
        abort(403)
    # 微信验证
    if request.method == 'GET':
        echo_str = request.args.get('echostr', '')
        return echo_str

    # POST request
    if encrypt_type == 'raw':
        # 明文模式
        msg = parse_message(request.data)
        # 事件处理
        if msg.type == 'event':
            # 关注事件
            if msg.event == 'subscribe':
                pass
                # mfc = MenuFunc(msg.source)
                # mfc.subscribecreatemenu()
            # reply = create_reply(msg.event, msg)
            if msg.event == 'click':
                if msg.key == 'CAMERA_ONE':
                    camera.get_img("/home/pi/Pictures/Camera/")
                if msg.key == 'CAMERA_SEQUENCE':
                    camera.get_img_sequence("/home/pi/Pictures/Camera/")
                if msg.key == 'CAMERA_CONTINUOUS':
                    camera.get_img_continuous("/home/pi/Pictures/Camera/")
                if msg.key == 'CAMERA_VIDEO':
                    camera.get_video("/home/pi/Pictures/Camera/")
        elif msg.type == 'text':
            reply = create_reply(msg.content, message=msg)
        elif msg.type == 'image':
            reply = create_reply('对不起，暂时不支持图片消息', message=msg)
        else:
            reply = create_reply(msg.type, message=msg)
        return reply.render()
    else:
        # 加密模式
        from wechatpy.crypto import WeChatCrypto

        crypto = WeChatCrypto(Config.TOKEN, Config.AES_KEY, Config.APPID)
        try:
            msg = crypto.decrypt_message(
                request.data,
                msg_signature,
                timestamp,
                nonce
            )
        except (InvalidSignatureException, InvalidAppIdException):
            abort(403)
        else:
            msg = parse_message(msg)
            if msg.type == 'text':
                reply = create_reply(msg.content, msg)
            else:
                reply = create_reply('Sorry, can not handle this for now', msg)
            return crypto.encrypt_message(reply.render(), nonce, timestamp)



